package huoye.shops.huoye.home.fragment;


import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.codeideology.android.AXIFragmentPagerAdapter;
import com.codeideology.android.utils.IntentUtils;
import com.codeideology.android.utils.StringUtils;
import com.codeideology.android.widget.convenientbanner.ConvenientBanner;
import com.codeideology.android.widget.convenientbanner.holder.CBViewHolderCreator;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import org.intellij.lang.annotations.RegExp;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import huoye.shops.R;
import huoye.shops.base.APIUrls;
import huoye.shops.base.BaseFragment;
import huoye.shops.base.UserManager;
import huoye.shops.huoye.home.adapter.BannerAdapter;
import huoye.shops.huoye.home.model.Banner;
import huoye.shops.huoye.home.model.MerchantCenter;
import huoye.shops.huoye.home.presenter.HomePresenter;
import huoye.shops.huoye.home.view.IHomeView;
import huoye.shops.huoye.mine.model.detialsImg;
import huoye.shops.utils.StockUtils;
import pub.devrel.easypermissions.EasyPermissions;

import static com.darsh.multipleimageselect.helpers.Constants.REQUEST_CODE;

/**
 * A simple {@link Fragment} subclass.
 */
public class HomeFragment extends BaseFragment implements IHomeView{



    List<Fragment> fragments = new ArrayList<>();
    List<String> titles = new ArrayList<>();
    AXIFragmentPagerAdapter myFragmentPagerAdapter;
    private HomePresenter mHomePresenter;


    @OnClick(R.id.home_btn_code)
    void onCodeClick(){

       /*  *//* 判断是否为6.0及其以上系统
                *//*
        if(Build.VERSION.SDK_INT > 23) {
            isPower();
        }else {
            makeToast("版本过低");
        }
*/
        isPower();
    }







    @BindView(R.id.home_banner)
    ConvenientBanner convenientBanner;

    @BindView(R.id.home_tl)
    TabLayout tl;
    @BindView(R.id.home_vp)
    ViewPager vp;


    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case 1311:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED&& grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                    getCode();
                } else {
                    makeToast("没有权限打开相机");
                }
                break;
            default:
        }
    }

    private void isPower(){
        if((ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA)!=PackageManager.PERMISSION_GRANTED)||ContextCompat.checkSelfPermission(getActivity().getBaseContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) !=PackageManager.PERMISSION_GRANTED){
            //如果没有授权，则请求授权
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1311);
            //String数组中为申请的权限，第一个是相机，第二个为修改内存，最后的参数即为申请授权的返回值，我设置的1311
        } else {
            getCode();
        }
    }
    private void getCode(){
        Intent intent = new Intent(getActivity(), CaptureActivity.class);
        startActivityForResult(intent,REQUEST_CODE);
    }



    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**
         * 处理二维码扫描结果
         */
        if (requestCode == REQUEST_CODE) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String url = bundle.getString(CodeUtils.RESULT_STRING);

                    String type = StockUtils.getValueByName(url, "type");
                    String itemId = StockUtils.getValueByName(url, "itemId");
                    String userId = StockUtils.getValueByName(url, "userId");
                    String num = StockUtils.getValueByName(url, "num");

                    mHomePresenter.postValidateAll(type,itemId,userId,num);

                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                   makeToast("解析二维码失败");
                }
            }
        }

    }







    @Override
    public int getContentViewId() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView(View view, @Nullable Bundle bundle) {

        mHomePresenter = new HomePresenter();
        mHomePresenter.addTaskListener(this);
        mHomePresenter.onStart();

        mHomePresenter.postMerchantCenter("All");
        initBanner();
    }

    @Override
    public void onResume() {
        super.onResume();
        if(mHomePresenter != null){
            mHomePresenter.postMerchantCenter("All");
        }
    }


    private void initBanner(){

        convenientBanner.setCanLoop(true);
        convenientBanner.startTurning(2000);
        convenientBanner.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });




        fragments.add(HomeDataShowFragment.getInstan(HomeDataShowFragment.PAGE_TYPE_TODAY));
        fragments.add(HomeDataShowFragment.getInstan(HomeDataShowFragment.PAGE_TYPE_ALL));
        titles.add(getString(R.string.home_today));
        titles.add(getString(R.string.home_all));


        StockUtils.reflex(tl);


        myFragmentPagerAdapter = new AXIFragmentPagerAdapter(getActivity().getSupportFragmentManager(),fragments, titles);
        vp.setAdapter(myFragmentPagerAdapter);
        vp.setOffscreenPageLimit(fragments.size());
        tl.setupWithViewPager(vp);

    }



    @Override
    public void setBanner(List<Banner> banner) {
        convenientBanner.setPages(
                new CBViewHolderCreator<BannerAdapter>() {
                    @Override
                    public BannerAdapter createHolder() {
                        BannerAdapter bannerAdapter = new BannerAdapter();
                        bannerAdapter.setOnBannerListener(new BannerAdapter.OnBannerListener() {
                            @Override
                            public void onBannerClick(Banner data) {
                                if (StringUtils.isNotEmpty(data.getUrl())) {
                                   // BaseTBWebViewActivity.startActivity(getActivity(), data.getTitle(), data.getUrl(), null);
                                }

                            }
                        });
                        return bannerAdapter;
                    }
                }, banner)
                .setPageIndicator(new int[]{R.mipmap.ic_page_indicator, R.mipmap.ic_page_indicator_focused});

    }

    @Override
    public void setData(MerchantCenter merchantCenter) {
        List<Banner> banners = new ArrayList<>();
        List<detialsImg> shopImgs = merchantCenter.getShopImgs();
        for (int i = 0; i < shopImgs.size() ; i++){
            Banner banner = new Banner();
            banner.setImgUrl(APIUrls.COMMON_CONFIG.TYPE_COMMON_ALIYUN+shopImgs.get(i).getImgUrl());
            banner.setTitle(shopImgs.get(i).getImgDes());
            banners.add(banner);
        }
        setBanner(banners);
    }









}
